package com.carpedil.shirodemo.system.controller;

import com.carpedil.shirodemo.common.util.ResultVO;
import com.carpedil.shirodemo.system.model.Dept;
import com.carpedil.shirodemo.system.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * 前端控制器
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Controller
@RequestMapping("/dept")
public class DeptController {
  @Autowired IDeptService deptService;

  /**
   * 跳转 部门管理页面
   *
   * @return /dept/dept-list
   */
  @GetMapping("/index")
  public String index() {
    return "/dept/dept-list";
  }

  /**
   * 跳转 新增部门页面
   *
   * @return /dept/dept-add
   */
  @GetMapping
  public String toAdd() {
    return "/dept/dept-add";
  }

  /**
   * 跳转 修改部门页面
   *
   * @param deptId deptId
   * @param map map
   * @return /dept/dept-add
   */
  @GetMapping("/{deptId}")
  public String update(@PathVariable("deptId") Integer deptId, ModelMap map) {
    map.addAttribute("dept", deptService.getById(deptId));
    return "/dept/dept-add";
  }

  /**
   * deptTree
   *
   * @return 所有部门树
   */
  @RequestMapping("/tree")
  @ResponseBody
  public ResultVO deptTree() {
    ResultVO success = ResultVO.success(deptService.selectAllDeptTree());
    return success;
  }

  /**
   * getDeptTreeRootList
   *
   * @return 所有部门树 + 导航目录
   */
  @GetMapping("/tree/root")
  @ResponseBody
  public ResultVO getDeptTreeRootList() {
    return ResultVO.success(deptService.getAllDeptTreeAndRoot());
  }

  /**
   * getChildListByDeptId
   *
   * @param parentId parentId
   * @return 根据部门parentId获取部门下的子部门
   */
  @GetMapping("/list")
  @ResponseBody
  public ResultVO getChildListByDeptId(Integer parentId) {
    return ResultVO.success(deptService.getChildListByDeptId(parentId));
  }

  /**
   * swapSort(Integer currentId, Integer swapId)
   *
   * @param currentId currentId
   * @param swapId swapId
   * @return 切换排序
   */
  @PostMapping("/swap")
  @ResponseBody
  public ResultVO swapSort(Integer currentId, Integer swapId) {
    deptService.swapSort(currentId, swapId);
    return ResultVO.success();
  }

  /**
   * addDept(Dept dept)
   *
   * @param dept dept
   * @return vo
   */
  @PostMapping
  @ResponseBody
  public ResultVO addDept(Dept dept) {
    deptService.insert(dept);
    return ResultVO.success();
  }

  /**
   * updateDept(Dept dept)
   *
   * @param dept dept
   * @return vo
   */
  @PutMapping
  @ResponseBody
  public ResultVO updateDept(Dept dept) {
    deptService.updateDept(dept);
    return ResultVO.success();
  }

  /**
   * deleteDept(@PathVariable("id") Integer id)
   *
   * @param id id
   * @return vo
   */
  @DeleteMapping("/{id}")
  @ResponseBody
  public ResultVO deleteDept(@PathVariable("id") Integer id) {
    System.out.println("id = " + id);
    deptService.deleteDeptById(id);
    return ResultVO.success();
  }
}
